from django.shortcuts import render
from django.views import View
from django.shortcuts import render, redirect
from django.http import HttpResponse
import re
from users.models import User


# Create your views here.
class IndexView(View):
    def get(self, request):
        return render(request, 'index.html')

#
# class UserRegisterView(View):
#     def get(self, request):
#         return render(request, 'register.html')


class Register(View):
    def get(self, request):

        return render(request, 'register.html')

    def post(self, request):
        # 获取表单数据
        data = request.POST
        user_name = data.get('user_name')
        pwd = data.get('pwd')
        cpwd = data.get('cpwd')
        phone = data.get('phone')
        sms_code = data.get('msg_code')
        allow = data.get('allow')
        # 验证表单数据
        if user_name is None or pwd is None or cpwd is None or phone is None or sms_code is None or allow is None:
            return render(request, 'register.html')
        # 验证用户名长度
        if len(user_name) > 20 or len(user_name) < 5:
            return HttpResponse('用户名长度不符合')

        # 验证用户名是否存在
        try:
            user = User.object.get(user_name=user_name)
        except:
            user = None
        if user:
            return HttpResponse('用户名以存在')

        # 验证两次密码是否一致
        if pwd != cpwd:
            return HttpResponse('两次密码不一致')

        # 验证手机号格式
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return HttpResponse('手机号格式不正确')

        # 验证短信验证码
        if len(sms_code) != 6:
            return HttpResponse('验证码不正确')

        User.objects.create_user(username=user_name, mobile=phone, password=pwd)

        return HttpResponse('首页')

